package org.huel.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.huel.backend.domain.entity.User;
import org.huel.backend.mapper.UserMapper;
import org.huel.backend.result.Result;
import org.huel.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;


/**
 * @author Liweijian.
 * @Description TODO
 * @date 2024/11/30 10:14
 */
@Service
public class UserServiceImpl implements UserService {

//    @Autowired
//    private UserMapper userMapper;
//
    @Override
    public Result login(User user) {
        // 根据用户名查询数据库的用户信息
        System.out.println(user);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getStudentId, user.getStudentId()); // 使用传入用户的 studentId 进行过滤
        User loginer = userMapper.selectOne(wrapper);
        System.out.println(loginer);
        if (loginer == null) {
            // 抛出一个自定义的异常
            return Result.error(500, "用户不存在");
        }
        if (!user.getPassword().equals(loginer.getPassword())) {
            return Result.error(500, "密码错误");
        }
        return Result.success("登录成功",loginer);
    }
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String studentId) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);

        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("User not found with student ID: " + studentId);
        }

        return new org.springframework.security.core.userdetails.User(
                user.getStudentId(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
        );
    }
    @Override
    public User getUserByStudentId(String studentId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);

        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("User not found with student ID: " + studentId);
        }
        return user;
    }

    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    @Transactional
    public User register(User request) {
        // 检查学号是否已存在
        if (checkStudentIdExists(request.getStudentId())) {
            throw new RuntimeException("该学号已被注册");
        }

        // 创建新用户
        User user = new User();
        user.setStudentId(request.getStudentId());
        user.setUserName(request.getUserName());
        user.setAddress(request.getAddress());
        user.setClassId(request.getClassId());

        // 直接存储明文密码，不进行加密
        user.setPassword(request.getPassword());

        // 保存用户
        userMapper.insert(user);

        // 返回用户信息（为安全起见，仍然清除密码）
        user.setPassword(null);
        return user;
    }

    @Override
    public boolean checkStudentIdExists(String studentId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        return userMapper.selectCount(queryWrapper) > 0;
    }
}
